package com.sita.redsun.connector.handler;

import com.google.common.io.BaseEncoding;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;




/**
 * Created by zhebinwang on 2017/4/1.
 * 这个类负责将服务器要发送的信息写出去，我们的顺序都是先写入object  再通过这个类的方法 将object写成
 * 字节流，然后  byteBuf.writeBytes 方法 发送字节流， 并且 ctx.flush(); 确认
 *
 * 向上发送也是一样，先收到字节流，然后转换成object进行处理，然后 业务处理。
 */
public class EncoderHandler extends MessageToByteEncoder<Object> {
    private Logger logger = LoggerFactory.getLogger(EncoderHandler.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, Object obj, ByteBuf byteBuf) throws Exception {

        byteBuf.writeBytes(BaseEncoding.base16().decode((String)obj));
        ctx.flush();
      /*
      //这些代码都是从冬哥处粘贴出来
        if (obj instanceof MtMessage){
            MtMessage mtMessage = (MtMessage) obj;
            String serviceData = mtMessage.getServiceData();
            byteBuf.writeBytes(BaseEncoding.base16().decode(serviceData));
            ctx.flush();
            logger.info("{} SEND_DATA {}", CFMotorServer.serverName, serviceData);
        } else if (obj instanceof PacketRes){
            PacketRes packetRes = (PacketRes) obj;
            byteBuf.writeBytes(packetRes.toBytes());
            ctx.flush();
            logger.info("{} SEND_DATA {}", CFMotorServer.serverName, BaseEncoding.base16().encode(packetRes.toBytes()));
        } else {
            String txt = (String) obj;
            byteBuf.writeBytes(txt.getBytes());
            ctx.flush();
            logger.info("{} SEND_DATA {}", CFMotorServer.serverName, txt);
        }*/
    }
}
